package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.DeptAndEmployeeDto;
import com.ysd.lis.dto.PubEmployeeDto;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.pub.PubEmployeeMapper;
import com.ysd.lis.mapper.sys.*;
import com.ysd.lis.request.PubEmployeeAddParam;
import com.ysd.lis.request.PubEmployeePageParam;
import com.ysd.lis.request.UserInfoVo;
import com.ysd.lis.service.PubEmployeeService;
import com.ysd.lis.service.SysUserDeptService;
import com.ysd.lis.service.SysUserRoleService;
import com.ysd.lis.service.SysUserService;
import com.ysd.lis.vo.PubEmployeeVo;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工表
 * 服务实现类
 * </p>
 *
 * @author LiuQi
 * @since 2023-10-19
 */
@Service
@Slf4j
public class PubEmployeeServiceImpl extends ServiceImpl<PubEmployeeMapper, PubEmployee> implements PubEmployeeService {

    private static final Logger logger = LoggerFactory.getLogger(PubEmployeeServiceImpl.class);


    @Autowired
    SysOrganizationMapper sysOrganizationMapper;
    @Autowired
    SysOrgDepartmentMapper sysOrgDepartmentMapper;
    @Autowired
    private PubEmployeeMapper pubEmployeeMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysUserDeptService sysUserDeptService;
    @Autowired
    private SysEmployeeDeptMapper sysEmployeeDeptMapper;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;


    @Override
    public Result findAllHisEmployeeListByOrgDept(PubEmployeePageParam pubEmployeePageParam) {
        String deptId = pubEmployeePageParam.getDeptId();
        String orgId = pubEmployeePageParam.getOrgId();
        // 1.机构 2.部门
        String orgDeptType = pubEmployeePageParam.getOrgDeptType();
        Page<PubEmployeeVo> page = new Page<>();
        page.setCurrent(pubEmployeePageParam.getPageIndex());
        page.setSize(pubEmployeePageParam.getPageSize());

        MPJLambdaWrapper<PubEmployee> mpjLambdaWrapper = new MPJLambdaWrapper();
        mpjLambdaWrapper.select(PubEmployee::getId, PubEmployee::getOrgId, PubEmployee::getDeptId, PubEmployee::getName, PubEmployee::getInputCode, PubEmployee::getCode, PubEmployee::getPosition, PubEmployee::getDuty, PubEmployee::getStrativeLevel, PubEmployee::getSeq).selectAs(SysOrganization::getName, PubEmployeeVo::getOrgName).selectAs(SysOrgDepartment::getName, PubEmployeeVo::getDeptName).leftJoin(SysOrganization.class, SysOrganization::getId, PubEmployee::getOrgId).leftJoin(SysOrgDepartment.class, SysOrgDepartment::getCode, PubEmployee::getDeptId).eq(PubEmployee::getDelFlag, "0");
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(pubEmployeePageParam.getSeachValue())) {
            mpjLambdaWrapper.and(wrapper ->
                    wrapper.like(PubEmployee::getName, pubEmployeePageParam.getSeachValue())
                            .or()
                            .like(PubEmployee::getCode, pubEmployeePageParam.getSeachValue())
                            .or().like(PubEmployee::getInputCode, pubEmployeePageParam.getSeachValue())
            );
        }

        if (StringUtils.isNotBlank(orgId)) {
            //查询此机构及机构下的所有子机构 orgDeptId
            mpjLambdaWrapper.eq(PubEmployee::getOrgId, orgId);

        }
        if (StringUtils.isNotBlank(deptId)) {
            //查询此部门及部门下所有的子部门
            mpjLambdaWrapper.eq(PubEmployee::getDeptId, deptId);
        }
        mpjLambdaWrapper.orderByAsc(PubEmployee::getSeq);


        IPage<PubEmployeeVo> hisEmployeeVoIPage = pubEmployeeMapper.selectJoinPage(page, PubEmployeeVo.class, mpjLambdaWrapper);
//        Page<PubEmployeeVo> hisEmployeeVoPage = pubEmployeeMapper.getHisEmployeePageList(page, pubEmployeePageParam);
        return Result.succ(1, "查询成功", hisEmployeeVoIPage);
    }

    @Override
    public Result finAllHisEmployeeList(String roleId) {
        MPJLambdaWrapper<SysUser> mpjLambdaWrapper = new MPJLambdaWrapper();
        mpjLambdaWrapper.selectAll(SysUser.class).leftJoin(SysUserRole.class, SysUserRole::getUserId, SysUser::getId).eq(SysUser::getDelFlag, "0").eq(SysUserRole::getRoleId, roleId);
        List<SysUser> sysUsers = sysUserMapper.selectList(mpjLambdaWrapper);
        LambdaQueryWrapper<PubEmployee> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(PubEmployee::getDelFlag, "0");
        List<PubEmployee> pubEmployees = pubEmployeeMapper.selectList(lambdaQueryWrapper);
        List<PubEmployee> collect1 = pubEmployees.stream().filter(em -> !sysUsers.stream().map(SysUser::getHisEmployeeCode).collect(Collectors.toList()).contains(em.getCode())).collect(Collectors.toList());
        return Result.succ(1, "查询成功", collect1);
    }

    @Override
    public Result finAllHisEmployeeList() {
        LambdaQueryWrapper<PubEmployee> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(PubEmployee::getDelFlag, "0");
        List<PubEmployee> pubEmployees = pubEmployeeMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", pubEmployees);
    }

    @Override
    public Result addHisEmployee(PubEmployeeAddParam pubEmployeeAddParam) {
        PubEmployee pubEmployee = new PubEmployee();
        BeanUtil.copyProperties(pubEmployeeAddParam, pubEmployee);
        pubEmployee.setEmpowerNum(SecureUtil.md5("123456"));
        // 根据code 和 name 查询用户表是否存在对应的用户 如果有 在用户表插入员工信息id 如果不在 则同步插入用户表数据
//        LambdaQueryWrapper<SysUser> userQuery = new LambdaQueryWrapper<>();
//        userQuery.eq(SysUser::getUsername, pubEmployee.getCode()).eq(SysUser::getRealname, pubEmployee.getName());
        int insert = pubEmployeeMapper.insert(pubEmployee);
//        List<SysUser> tUsers = sysUserMapper.selectList(userQuery);
//        if (tUsers.size() > 0) {
//            SysUser tUser = new SysUser();
//            BeanUtil.copyProperties(tUsers.get(0), tUser);
//            tUser.setHisEmployeeId(pubEmployee.getId());
//            int i = sysUserMapper.updateById(tUser);
//        } else {
//            SysUser tUser = new SysUser();
//            tUser.setDeptId(pubEmployeeAddParam.getDeptId());
//            tUser.setUsername(pubEmployeeAddParam.getCode());
//            tUser.setRealname(pubEmployeeAddParam.getName());
//            tUser.setEnable("0");
//            tUser.setPassword(SecureUtil.md5("123456"));
//            tUser.setOrgId(pubEmployeeAddParam.getOrgId());
//            tUser.setHisEmployeeId(pubEmployee.getId());
//            sysUserMapper.insert(tUser);
//        }
        if (insert > 0) {
            return Result.succ(1, "添加成功", pubEmployee.getId());
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result editHisEmployee(PubEmployeeAddParam pubEmployeeAddParam) {
        PubEmployee pubEmployee = new PubEmployee();
        BeanUtil.copyProperties(pubEmployeeAddParam, pubEmployee);
        int i = pubEmployeeMapper.updateById(pubEmployee);
        if (i > 0) {
            return Result.succ(1, "更新成功", i);
        } else {
            return Result.fail("更新失败！");
        }
    }

    @Transactional
    @Override
    public Result deleteHisEmployeeById(String id) {
        PubEmployee pubEmployee = new PubEmployee();
        pubEmployee.setId(id);
        pubEmployee.setDelFlag(1);
        int d = pubEmployeeMapper.updateById(pubEmployee);
        // 删除与用户的关联关系
        deleteUserContactById(id, "1");
        if (d > 0) {
            return Result.succ(1, "删除成功", d);
        } else {
            return Result.fail("删除失败！");
        }
    }

    /**
     * 根据员工id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Result getHisEmployeeInfoById(String id) {
        PubEmployee pubEmployee = pubEmployeeMapper.selectById(id);
        return Result.succ(1, "查询成功", pubEmployee);
    }

    @Override
    public Result getSignatureFilePath(String id) {
        PubEmployee pubEmployee = (PubEmployee) getHisEmployeeInfoById(id).getData();
        File file = new File(pubEmployee.getSignatureUrl());
        String fileName1 = file.getName();
        String filename = "/image/" + fileName1;
        return Result.succ(1, "查询成功", filename);
    }

    /**
     * 根据id查询关联用户列表
     *
     * @param id
     * @return
     */
    @Override
    public Result getUserListByHisEmployeeId(String id) {
        LambdaQueryWrapper<SysUser> userMapperQuery = new LambdaQueryWrapper();
        userMapperQuery.eq(SysUser::getHisEmployeeId, id);
        List<SysUser> sysUsers = sysUserMapper.selectList(userMapperQuery);
        return Result.succ(1, "查询成功", sysUsers);
    }

    /**
     * 根据用户id或者员工id删除关联关系
     * 0:单条删除 1:多条删除
     *
     * @param id, type
     * @return
     */
    @Override
    public Result deleteUserContactById(String id, String type) {
        LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if ("0".equals(type)) {
            lambdaUpdateWrapper.set(SysUser::getHisEmployeeId, null).eq(SysUser::getId, id);
        } else {
            lambdaUpdateWrapper.set(SysUser::getHisEmployeeId, null).eq(SysUser::getHisEmployeeId, id);
        }
        int update = sysUserMapper.update(null, lambdaUpdateWrapper);
        if (update > 0) {
            return Result.succ(1, "删除成功", update);
        } else {
            return Result.fail("删除失败！");
        }
    }

    /**
     * 根据 用户id 和 员工id 添加关联关系
     *
     * @param hisEmployeeId，userId
     * @return
     */
    @Override
    public Result addContactUserInfo(String hisEmployeeId, String userId) {
        LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(SysUser::getHisEmployeeId, hisEmployeeId).eq(SysUser::getId, userId);
        int update = sysUserMapper.update(null, lambdaUpdateWrapper);
        if (update > 0) {
            return Result.succ(1, "添加关联关系成功", update);
        } else {
            return Result.fail("添加关联关系失败！");
        }
    }

    /**
     * 修改授权码
     *
     * @param id
     * @param empowerNum
     * @return
     */
    @Override
    public Result updateEmpowerNum(String id, String empowerNum) {
        LambdaUpdateWrapper<PubEmployee> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(PubEmployee::getEmpowerNum, SecureUtil.md5(empowerNum)).eq(PubEmployee::getId, id);
        int update = pubEmployeeMapper.update(null, lambdaUpdateWrapper);
        if (update > 0) {
            return Result.succ(1, "更新验证码成功", update);
        } else {
            return Result.fail("更新验证码失败！");
        }
    }

    /**
     * 根据id查询关联部门列表
     *
     * @param id
     * @return
     */
    @Override
    public Result getDeptListByHisEmployeeId(String id) {
        MPJLambdaWrapper<SysEmployeeDept> wrapper = new MPJLambdaWrapper<>();
        wrapper.select(SysEmployeeDept::getId).select(SysEmployeeDept::getIsDefault).selectAs(SysOrgDepartment::getId, DeptAndEmployeeDto::getDeptId).selectAs(SysOrgDepartment::getCode, DeptAndEmployeeDto::getDeptCode).selectAs(SysOrgDepartment::getName, DeptAndEmployeeDto::getDeptName).leftJoin(SysOrgDepartment.class, SysOrgDepartment::getId, SysEmployeeDept::getDeptId).eq(SysEmployeeDept::getHisEmployee, id);
        List<DeptAndEmployeeDto> list = sysEmployeeDeptMapper.selectJoinList(DeptAndEmployeeDto.class, wrapper);
        return Result.succ(1, "查询成功", list);
    }

    /**
     * 添加用户与部门的关联关系
     *
     * @param hisEmployeeId
     * @param deptId
     * @return
     */
    @Override
    public Result addContactDeptInfo(String hisEmployeeId, String deptId) {
        //添加之前先查看是否有此关联数据，如果有则不添加
        LambdaQueryWrapper<SysEmployeeDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysEmployeeDept::getHisEmployee, hisEmployeeId).eq(SysEmployeeDept::getDeptId, deptId).eq(SysEmployeeDept::getDelFlag, 0);
        Integer selectCount = sysEmployeeDeptMapper.selectCount(queryWrapper);
        if (selectCount > 0) {
            return Result.succ(1, "已存在关联关系！", null);
        } else {
            SysEmployeeDept sysEmployeeDept = new SysEmployeeDept();
            sysEmployeeDept.setHisEmployee(hisEmployeeId);
            sysEmployeeDept.setDeptId(deptId);
            int insert = sysEmployeeDeptMapper.insert(sysEmployeeDept);
            if (insert > 0) {
                return Result.succ(1, "添加关联关系成功", insert);
            } else {
                return Result.fail("添加关联关系失败！");
            }
        }
    }

    @Override
    public Result setDefaultDeptByHisEmployeeId(String id, String employeeId) {
        //先把所有得改为非默认
        LambdaUpdateWrapper<SysEmployeeDept> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SysEmployeeDept::getIsDefault, "1").eq(SysEmployeeDept::getHisEmployee, employeeId);
        int update = sysEmployeeDeptMapper.update(null, updateWrapper);
        SysEmployeeDept sysEmployeeDept = new SysEmployeeDept();
        sysEmployeeDept.setId(id);
        sysEmployeeDept.setIsDefault("0");
        int updateById = sysEmployeeDeptMapper.updateById(sysEmployeeDept);
        if (updateById > 0) {
            return Result.succ("修改成功");
        } else {
            return Result.fail("修改失败！");
        }
    }

    @Override
    public Result getEmployeePageList(PubEmployeePageParam pageParam) {
        Page<PubEmployee> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<PubEmployee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PubEmployee::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(PubEmployee::getName, pageParam.getSeachValue()).or().like(PubEmployee::getCode, pageParam.getSeachValue()));
        }
        Page<PubEmployee> pubEmployeePage = pubEmployeeMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", pubEmployeePage);
    }


    /**
     * 根据用户id或者部门id删除关联关系
     * type  0:单条删除 1:多条删除
     *
     * @param id, type
     * @return
     */
    @Override
    public Result deleteDeptContactById(String id, String type) {
        LambdaQueryWrapper<SysEmployeeDept> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if ("0".equals(type)) {
            lambdaQueryWrapper.eq(SysEmployeeDept::getId, id);
        } else {
            lambdaQueryWrapper.eq(SysEmployeeDept::getHisEmployee, id);
        }
        int delete = sysEmployeeDeptMapper.delete(lambdaQueryWrapper);
        if (delete > 0) {
            return Result.succ(1, "删除成功", delete);
        } else {
            return Result.fail("删除失败！");
        }
    }


    /**
     * 更新电子签名路径
     *
     * @param id
     * @param signatureUrl
     * @return
     */
    @Override
    public Result uploadSignatureFile(String id, String signatureUrl) {
        LambdaUpdateWrapper<PubEmployee> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(PubEmployee::getSignatureUrl, signatureUrl).eq(PubEmployee::getId, id);
        int update = pubEmployeeMapper.update(null, lambdaUpdateWrapper);
        if (update > 0) {
            return Result.succ(1, "上传电子签名成功", update);
        } else {
            return Result.fail("上传电子签名失败！");
        }
    }

    public List<PubEmployee> findEmployeeListByIds(List<String> employeeIds) {
        LambdaQueryWrapper<PubEmployee> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(PubEmployee::getDelFlag, "0").in(PubEmployee::getId, employeeIds);
        return pubEmployeeMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public Result getEmployeeByCodeAndNum(PubEmployee employee) {
        if (ToolsUtils.isEmpty(employee)) {
            return Result.fail("入参信息不可为空！");
        }
        if (ToolsUtils.isEmpty(employee.getCode())) {
            return Result.fail("员工编号不可为空！");
        }
        if (ToolsUtils.isEmpty(employee.getEmpowerNum())) {
            return Result.fail("授权码不可为空！");
        }
        String empowerNum = SecureUtil.md5(employee.getEmpowerNum());
        LambdaQueryWrapper<PubEmployee> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(PubEmployee::getDelFlag, "0").eq(PubEmployee::getCode, employee.getCode()).eq(PubEmployee::getEmpowerNum, empowerNum);

        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isNotEmpty(sysUser)) {
            lambdaQueryWrapper.eq(PubEmployee::getOrgId, sysUser.getOrgId());
        }
        List<PubEmployee> list = pubEmployeeMapper.selectList(lambdaQueryWrapper);
        if (ToolsUtils.isEmpty(list) || list.size() > 1) {
            return Result.fail("请检查账号与授权码是否正确或员工编号是否唯一！");
        }
        return Result.succ(list.get(0));
    }

    @Override
    public List<UserInfoVo> finAllHisEmployees(String info) {
        LambdaQueryWrapper<PubEmployee> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(PubEmployee::getDelFlag, "0");
        List<PubEmployee> pubEmployees = pubEmployeeMapper.selectList(lambdaQueryWrapper);

        List<UserInfoVo> userInfoVoList = new ArrayList<>();

        for (PubEmployee employee : pubEmployees) {
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtil.copyProperties(employee, userInfoVo);
            userInfoVoList.add(userInfoVo);
        }
        return userInfoVoList;
    }

    @Override
    public Result syncPubEmployees() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);


        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                PubEmployee pubEmployee = new PubEmployee();
                pubEmployee.setOrgId(orgId);
                for (String webUrl : collect) {
                    logger.info("接口地址为："+webUrl);
                    String returnMsg1 = HttpUtil.createPost(webUrl + "/public/syncSysEmployee").body(JSONUtil.toJsonStr(pubEmployee)).contentType("application/json").execute().body();
                    logger.info("参数返回："+returnMsg1);
                    JSONObject reportObject = new JSONObject(returnMsg1);
                    JSONObject reportStatus = reportObject.getJSONObject("status");
                    String reportCode = reportStatus.get("code").toString();
                    if ("400".equals(reportCode)) {
                        return Result.fail("接口管理平台异常,请检查");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("接口管理平台异常,请检查");
        }
        return Result.succ(1, "请求成功", null);
    }

    @Override
    public Result hisEmployeeBatchCreateUser(PubEmployeeDto dto) {
        List<PubEmployee> createUserEmployeeList;
        List<PubEmployee> pubEmployeeList = dto.getPubEmployeeList();
        List<String> ids = pubEmployeeList.stream().map(PubEmployee::getId).collect(Collectors.toList());
        //根据员工ID查出用户表中关联得数据
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDelFlag, 0)
                .in(SysUser::getHisEmployeeId, ids);
        List<SysUser> userList = sysUserMapper.selectList(queryWrapper);
        if (ToolsUtils.isNotEmpty(userList)) {
            List<String> existIds = userList.stream().map(SysUser::getHisEmployeeId).distinct().collect(Collectors.toList());
            List<PubEmployee> collect = pubEmployeeList.stream().filter(p -> !existIds.contains(p.getId())).collect(Collectors.toList());
            createUserEmployeeList = collect;
        } else {
            createUserEmployeeList = pubEmployeeList;
        }
        if (ToolsUtils.isNotEmpty(createUserEmployeeList)) {
            List<SysUser> createSysUserList = new ArrayList<>();
            for (PubEmployee c : createUserEmployeeList) {
                SysUser sysUser = new SysUser();
                sysUser.setOrgId(c.getOrgId());
                sysUser.setUsername(c.getCode());
                sysUser.setCode(c.getCode());
                sysUser.setPassword(SecureUtil.md5("123456"));
                sysUser.setRealname(c.getName());
                sysUser.setHisNo(c.getCode());
                sysUser.setEnable("1");
                sysUser.setHisEmployeeId(c.getId());
                sysUser.setDeptId(c.getDeptId());
                createSysUserList.add(sysUser);
            }

            boolean b = sysUserService.saveBatch(createSysUserList);
            if (b) {
                //添加用户部门
                List<SysUserDept> sysUserDeptList = new ArrayList<>();
                for (SysUser sysUser : createSysUserList) {
                    if (StringUtils.isNotBlank(sysUser.getDeptId())) {
                        SysUserDept userDept = new SysUserDept();
                        userDept.setUserId(sysUser.getId());
                        userDept.setDeptId(sysUser.getDeptId());
                        sysUserDeptList.add(userDept);
                    }
                }
                sysUserDeptService.saveBatch(sysUserDeptList);

                LambdaQueryWrapper<SysRole> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(SysRole::getDelFlag, 0)
                        .eq(SysRole::getCode, "CZY");
                SysRole sysRole = sysRoleMapper.selectOne(queryWrapper1);
                if (null != sysRole) {
                    //添加用户角色
                    List<SysUserRole> userRoleList = new ArrayList<>();
                    for (SysUser sysUser : createSysUserList) {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(sysUser.getId());
                        sysUserRole.setRoleId(sysRole.getId());
                        userRoleList.add(sysUserRole);

                    }
                    sysUserRoleService.saveBatch(userRoleList);
                }

            }


        }


        return Result.succ(1, "更新成功", null);

    }

    @Override
    public Result getPubEmployeeList(PubEmployeePageParam pageParam) {
        LambdaQueryWrapper<PubEmployee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PubEmployee::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(PubEmployee::getName, pageParam.getSeachValue()).or().like(PubEmployee::getCode, pageParam.getSeachValue()));
        }
        List<PubEmployee> pubEmployees = pubEmployeeMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", pubEmployees);
    }

    @Override
    public Result hisEmployeeBatchCreateHSUser(PubEmployeeDto dto) {

        List<PubEmployee> createUserEmployeeList;
        List<PubEmployee> pubEmployeeList = dto.getPubEmployeeList();
        List<String> ids = pubEmployeeList.stream().map(PubEmployee::getId).collect(Collectors.toList());
        //根据员工ID查出用户表中关联得数据
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDelFlag, 0)
                .in(SysUser::getHisEmployeeId, ids);
        List<SysUser> userList = sysUserMapper.selectList(queryWrapper);
        if (ToolsUtils.isNotEmpty(userList)) {
            List<String> existIds = userList.stream().map(SysUser::getHisEmployeeId).distinct().collect(Collectors.toList());
            List<PubEmployee> collect = pubEmployeeList.stream().filter(p -> !existIds.contains(p.getId())).collect(Collectors.toList());
            createUserEmployeeList = collect;
        } else {
            createUserEmployeeList = pubEmployeeList;
        }
        if (ToolsUtils.isNotEmpty(createUserEmployeeList)) {
            List<SysUser> createSysUserList = new ArrayList<>();
            for (PubEmployee c : createUserEmployeeList) {
                SysUser sysUser = new SysUser();
                sysUser.setOrgId(c.getOrgId());
                sysUser.setUsername(c.getCode());
                sysUser.setCode(c.getCode());
                sysUser.setPassword(SecureUtil.md5("123456"));
                sysUser.setRealname(c.getName());
                sysUser.setHisNo(c.getCode());
                sysUser.setEnable("1");
                sysUser.setHisEmployeeId(c.getId());
                sysUser.setDeptId(c.getDeptId());
                createSysUserList.add(sysUser);
            }

            boolean b = sysUserService.saveBatch(createSysUserList);
            if (b) {
                //添加用户部门
                List<SysUserDept> sysUserDeptList = new ArrayList<>();
                for (SysUser sysUser : createSysUserList) {
                    if (StringUtils.isNotBlank(sysUser.getDeptId())) {
                        SysUserDept userDept = new SysUserDept();
                        userDept.setUserId(sysUser.getId());
                        userDept.setDeptId(sysUser.getDeptId());
                        sysUserDeptList.add(userDept);
                    }
                }
                sysUserDeptService.saveBatch(sysUserDeptList);

                LambdaQueryWrapper<SysRole> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(SysRole::getDelFlag, 0)
                        .eq(SysRole::getCode, "1002");
                SysRole sysRole = sysRoleMapper.selectOne(queryWrapper1);
                if (null != sysRole) {
                    //添加用户角色
                    List<SysUserRole> userRoleList = new ArrayList<>();
                    for (SysUser sysUser : createSysUserList) {
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(sysUser.getId());
                        sysUserRole.setRoleId(sysRole.getId());
                        userRoleList.add(sysUserRole);

                    }
                    sysUserRoleService.saveBatch(userRoleList);
                }

            }


        }


        return Result.succ(1, "更新成功", null);


    }
}
